package it.koutifaris.travianmap.dal.sqlservices.tile;

import it.koutifaris.travianmap.dal.sqlservices.MapSqlContract.Alliances;
import it.koutifaris.travianmap.dal.sqlservices.MapSqlContract.Players;
import it.koutifaris.travianmap.dal.sqlservices.MapSqlContract.Revisions;
import it.koutifaris.travianmap.dal.sqlservices.MapSqlContract.Villages;
import it.koutifaris.travianmap.model.Tribe;
import it.koutifaris.travianmap.model.Village;
import it.koutifaris.travianmap.model.impl.AllianceImpl;
import it.koutifaris.travianmap.model.impl.PlayerImpl;
import it.koutifaris.travianmap.model.impl.VillageImpl;
import it.koutifaris.travianmap.utils.cursor.ColumnNameCursor;
import it.koutifaris.travianmap.utils.cursor.ColumnNameCursorWrapper;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;

class MapDataExtractor {

	MapDataExtractor() {
	}

	List<Village> getVillagesFromCursor(Cursor cursor) {
		List<Village> villages = new ArrayList<Village>();
		while (cursor.moveToNext()) {
			villages.add(getVillageFromCursor(cursor));
		}

		return villages;
	}

	private Village getVillageFromCursor(Cursor originalCursor) {
		ColumnNameCursor cursor = new ColumnNameCursorWrapper(originalCursor);

		int id = cursor.getInt(Villages.COLUMN_NAME_VILLAGE_ID);
		String name = cursor.getString(Villages.COLUMN_NAME_VILLAGE_NAME);
		int population = cursor.getInt(Villages.COLUMN_NAME_POPULATION);
		int x = cursor.getInt(Villages.COLUMN_NAME_X);
		int y = cursor.getInt(Villages.COLUMN_NAME_Y);

		return new VillageImpl(id, name, getPlayerFromCursor(cursor), population, x, y);
	}

	private PlayerImpl getPlayerFromCursor(ColumnNameCursor cursor) {
		int playerId = cursor.getInt(Players.COLUMN_NAME_PLAYER_ID);
		long revisionId = cursor.getLong(Revisions.COLUMN_NAME_REVISION_ID);
		String name = cursor.getString(Players.COLUMN_NAME_PLAYER_NAME);
		Tribe tribe = Tribe.valueOf(cursor.getInt(Players.COLUMN_NAME_TRIBE));

		return new PlayerImpl(
				playerId,
				name,
				tribe,
				getAllianceFromCursor(cursor),
				new VillagesLoaderImpl(playerId, revisionId));
	}

	private AllianceImpl getAllianceFromCursor(ColumnNameCursor cursor) {
		int id = cursor.getInt(Alliances.COLUMN_NAME_ALLIANCE_ID);
		String name = cursor.getString(Alliances.COLUMN_NAME_ALLIANCE_NAME);

		return new AllianceImpl(id, name);
	}
}
